﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using RATSharpW7.ViewModel;
using System.Windows.Navigation;
using RATSharp.Model;
using Coding4Fun.Toolkit.Controls;
using Microsoft.Phone.Shell;

namespace RATSharpW7.View
{
    /// <summary>
    /// Create reservation screen specific to
    /// PickUp action - so dates FROM, PERIODICAL and VALID are disabled
    /// </summary>
    public partial class CreatePickUpReservation : PhoneApplicationPage
    {

        bool isNewPageInstance = false;
        PeriodViewModel model;

        public CreatePickUpReservation()
        {
            InitializeComponent();

            isNewPageInstance = true;
        }

        protected override void OnNavigatedFrom(System.Windows.Navigation.NavigationEventArgs e)
        {
            if (e.NavigationMode !=
                  System.Windows.Navigation.NavigationMode.Back)
            {
                State["PeriodViewModel"] = model;
            }
        }

        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            if (isNewPageInstance)
            {
                if (model == null)
                {
                    if (State.ContainsKey("PeriodViewModel"))
                    {
                        model = State["PeriodViewModel"]
                                           as PeriodViewModel;
                    }
                    else
                    {
                        var data = NavigationContext.GetData<RATSharp.Model.ReservationFactory.CreateReservationData>();
                        period period = ReservationFactory.createNewReservation(data, UserViewModel.UserContext.Name);

                        model = new PeriodViewModel(period, data.obj);
                    }
                }
                DataContext = model;
            }
            isNewPageInstance = false;
            initActionBar();
        }



        private void toDatePicker_ValueChanged(object sender, DateTimeValueChangedEventArgs e)
        {
            DateTimePickerBase picker = sender as DateTimePickerBase;

            if (e.OldDateTime.HasValue && e.NewDateTime.HasValue && e.OldDateTime.Value != e.NewDateTime.Value)
            {
                string message;
                if (!model.validateDateBeforeNow(e.NewDateTime.Value, out message)  )
                {
                    ViewUtils.reportError(message);
                    // quite dirty hack in here. But Binding isnt helpful here - we need to validate
                    // dates knowing what the old datetime value was. Only way how to archieve that is this listener.
                    //We cant do that on model level - periods sure can be placed in the past, this validation
                    //is only related to create/edit form
                    //Solution would be use OneWay binding, but it is not working with trirdparty pickers!
                    //(see http://jesperbjerre.wordpress.com/2012/08/09/wp-datepicker-oneway-databinding-problem/)
                    //So we need to stop somewhere in updating  - and deregister ourselves is the
                    //way how to archieve that
                    picker.ValueChanged -= toDatePicker_ValueChanged;
                    picker.Value = e.OldDateTime.Value;
                    picker.ValueChanged += toDatePicker_ValueChanged;
                    return;
                }
                model.DataSource.ToDate = e.NewDateTime.Value;
            }
        }

        private void initActionBar()
        {
            this.ApplicationBar = new ApplicationBar();
            this.ApplicationBar.IsVisible = true;
            this.ApplicationBar.Opacity = 1;
            ApplicationBarIconButton createNewReservationButton = new ApplicationBarIconButton(new Uri("/Images/submit.png", UriKind.RelativeOrAbsolute));
            createNewReservationButton.Text = Application.Current.Resources["AddReservationLabel"] as string;
            createNewReservationButton.Click += new EventHandler(createNewReservationButton_Click);
            this.ApplicationBar.Buttons.Add(createNewReservationButton);
            ApplicationBarMenuItem viewObjectItem = new ApplicationBarMenuItem();
            viewObjectItem.Text = Application.Current.Resources["ViewObjectLabel"] as string;
            viewObjectItem.Click += new EventHandler(viewObjectButton_Click);
            this.ApplicationBar.MenuItems.Add(viewObjectItem);
        }

        private void viewObjectButton_Click(object sender, EventArgs e)
        {
            model.loadObject(model.DataSource.reservation.objectId, new EventHandler<PeriodViewModel.LoadObjectEventArgs>(objectLoaderHandler));
        }

        private void objectLoaderHandler(object sender, PeriodViewModel.LoadObjectEventArgs e)
        {
            if (e.succesfull)
            {
                NavigationService.Navigate("View", typeof(SimpleObjectProfile), e.obj);
            }
        }



        private void createNewReservationButton_Click(object sender, EventArgs e)
        {
            model.submitChanges(new EventHandler<ModifyReservationEventArgs>(reservationSubmittedHandler));
        }

        private void reservationSubmittedHandler(object sender, ModifyReservationEventArgs e)
        {
            if (!e.succesfull)
            {
                ViewUtils.reportError(e.message);
            }
            else
            {
                if (NavigationService.CanGoBack)
                {
                    NavigationService.GoBack();
                }
            }

        }
    }
}